<template>
  <div class="root">
    <div class="content-layout">
      <!-- 编辑内容 -->
      <div class="left-layout" v-show="step == 1">
        <el-row>
          <span style="font-color: black; font-weight:bold">合同编辑</span>
          <el-button size="small" type="primary" round style="margin-left:10px" @click="onCaseDetail">查看进件信息</el-button>
          <el-button size="small" type="info" round style="margin-left:10px" @click="onReset">重置编辑信息</el-button>
        </el-row>
        <PresetForm style="margin-top: 10px;" ref="presetform" :initialForm="initialForm" :fieldsets="initContractTemplate()" />
      </div>
      <!-- 预览 -->
      <div class="right-layout" v-show="step == 2">
        <div style="height: 5%; align-items:center; display:flex">
          <span style="font-weight: bold; color: black; margin-left: 10px; font-size: 16px">合同预览</span>
        </div>
        <iframe id="myFrame" style="width: 99%; margin-left: 0.5%; margin-right: 0.5%; height: 94%; background-color:white" :srcdoc="perviewData" align="center" frameborder="0"></iframe>
      </div>
    </div>
    <div class="bottom-layout">
      <el-button type="info" style="width: 120px;" @click="onBack">返回</el-button>
      <el-button type="danger" style="width: 120px; margin-left: 7vh" @click="onSave" v-if="step == 1">暂存</el-button>
      <el-button type="primary" style="width: 120px; margin-left: 7vh" @click="onSubmit"> {{ step == 1 ? '提交' : '提交用印'}}</el-button>
    </div>
    <el-dialog 
      width="30%"
      :show-close="false"
      :close-on-click-modal="false"
      :visible.sync="isShowFinishDialog"
      append-to-body>
      <Loading v-if="isShowFinishDialog" :submitResult="submitResult" @onFinish="onFinish" @onBack="onLoadingBack"></Loading>
    </el-dialog>      
  </div>
</template>

<script>
import PresetForm from "./PresetForm";
import {loanContract} from '../js/contractTemplate.js'
import {dalianEntrustContract} from '../js/dalianEntrustContract.js'
import { mortgageTemplate } from '../js/mortgageTemplate.js'
import { changchunMortgageTemplate } from '../js/changchunMortgageTemplate.js'
import { changchunApplyChart } from '../js/changchunApplyChart.js'
import { changchunEntrustContract } from '../js/changchunEntrustContract.js'
import { jilinMortgageTemplate } from '../js/jilinMortgageTemplate.js'
import { jilinApplyChart } from '../js/jilinApplyChart.js'
import { dalianApplyChart } from '../js/dalianApplyChart.js'
import { common } from '@/utils/common'
import Loading from './Loading.vue'
import api from '../api';
import { CONSTANT_OBJ } from '@/utils/constant'
export default {
  props: {
    caseId: String,
    city: String, // 城市
    contractNo: String,
    productType: String,
    generateId: String
  },
  components: {
    PresetForm, Loading
  },
  data () {
    return {
      loanContract,// 全部-借款合同
      dalianEntrustContract, // 大连委托书
      mortgageTemplate, // 全部-抵押合同
      changchunMortgageTemplate, // 长春-抵押合同
      changchunApplyChart, // 长春-申请表
      changchunEntrustContract, // 长春-委托书
      jilinMortgageTemplate, // 吉林-抵押合同
      jilinApplyChart, // 吉林-申请表
      dalianApplyChart, // 大连-申请表
      perviewData: '',
      step: 1,
      isShowFinishDialog: false,
      submitResult: '', // 提交结果 1生成成功  2生成不成功
      initialForm: {}
    }
  },
  computed: {
    // 初始化合同模板
    initContractTemplate () {
      return function () {
        let contract = null
        switch (this.contractNo) {
          case '2022': // 借款合同
            contract = this.loanContract
            break
          case '2023': // 抵押合同
            contract = this.mortgageTemplate
            break
          case '2024': // 大连-申请表
            contract = this.dalianApplyChart
            break
          case '2025': // 大连-委托书
            contract = this.dalianEntrustContract
            break
          case '2026': // 吉林-抵押合同
            contract = this.jilinMortgageTemplate
            break
          case '2027': // 吉林-申请表
            contract = this.jilinApplyChart
            break
          case '2028': // 长春-抵押合同
            contract = this.changchunMortgageTemplate
            break
          case '2029': // 长春-申请表
            contract = this.changchunApplyChart
            break
          case '2030': // 长春-委托书
            contract = this.changchunEntrustContract
            break
        }
        return contract
      }
    }
  },
  created () {
    console.log('>>>>>contractNo:', this.contractNo);
    this.getDetail();
  },
  methods: {
    onCaseDetail () {
      const { caseId, productType } = this;
      const link = `/marketing/mainLayout/?tabName=QUERY_CASE&caseId=${caseId}&productType=${productType}`
      window.open(link, '_blank').focus();
    },
    onBack () {
      if (this.step == 1) {
        this.$emit('onBack')
      } else {
        this.step = 1
      }
    },
    onLoadingBack () {
      this.isShowFinishDialog = false
    },
    /**
     * 重置字段
     */
    onReset () {
      if (this.initialForm) {
        Object.keys(this.$refs.presetform.form).forEach(key => {
          if (!this.initialForm[key]) {
            if (this.$refs.presetform.form[key] instanceof Array) {
              this.$refs.presetform.form[key] = []
            } else {
              this.$refs.presetform.form[key] = ''
            }
          } else {
            this.$refs.presetform.form[key] = this.initialForm[key]
          }
        })
      } else {
        Object.keys(this.$refs.presetform.form).forEach(key => {
          if (this.$refs.presetform.form[key] instanceof Array) {
            this.$refs.presetform.form[key] = []
          } else {
            this.$refs.presetform.form[key] = ''
          }
        })
      }
    },
    // 用印完成
    onFinish () {
      this.isShowFinishDialog = false
      this.$emit('onFinish')
    },
    // 获取回显内容
    getDetail () {
      let params = {
        city: this.city,
        caseId: this.caseId,
        contractTemplateNo: this.contractNo,
        generateId: this.generateId
      }
      api.generateMortgageContract(params).then(res => {
        const {responseCode, data} = res 
        if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
          if (data) {
            this.initialForm = JSON.parse(data.contractFields || '{}')
          }
        }
      }).catch (() => {})
      
    },
    setDeafultData (data) {
      Object.keys(data).forEach(key => {
        if (data[key] instanceof Array) {
          // 对多选数据进行排序
          if (data[key] && data[key].length > 0) {
            data[key].sort()
          }
        } else {
          if (!data[key]) {
            data[key] = ''
          }
        }
      })
    },
    // 暂存
    onSave () {
      this.saveMortgageContract(true)
    },
    saveMortgageContract (isShowTip) {
      let data = {...this.$refs.presetform.form}
      console.log('>>>暂存<<<', data);
      // 对没填写的内容赋控制
      this.setDeafultData(data)
      let params = {
        caseId: this.caseId,
        contractTemplateNo: this.contractNo,
        contractFields: JSON.stringify(data),
        city: this.city,
        generateId: this.generateId
      }
      console.log('>>>暂存<<<', params);
      api.saveMortgageContract(params).then(res => {
        const {responseCode, data} = res
        if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
          if (isShowTip) {
            this.$notify({
              title: '暂存成功',
              message: '编辑的协议内容已经保存。',
              type: 'success',
              position: 'bottom-right',
              duration: 1000
            });
          } else {
            // 预览数据
            this.perviewData = data.contractStr || ''
          }
        }
      }).catch(() => {})
    },
    // 提交
    onSubmit () {
      if(this.step == 1) {
        this.step = 2
        console.log('>>>预览<<<', this.step);
        // 暂存一次 - 获取预览
        this.saveMortgageContract(false)
      } else {
        let data = {...this.$refs.presetform.form}
        console.log('>>提交<<', data);
        common.confirmFn('是否确定提交用印？', '提交用印后合同不可修改！').then(res => {
          if (res) {
            this.submitResult = ''
            this.isShowFinishDialog = true
            let params = {
              caseId: this.caseId,
              contractTemplateNo: this.contractNo,
              contractFields: JSON.stringify(data),
              city: this.city,
              generateId: this.generateId
            }
            api.submitStampMortgageContract(params).then(res => {
              const {responseCode} = res
              if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
                this.submitResult = '1'
              } else {
                this.submitResult = '2'
              }
            }).catch (() => {
              this.submitResult = '2'
            })
          }
        })
      }
    }
  }
}
</script>
<style lang="less">
.root {
  .content-layout{
    display: flex;
    overflow-y: auto;
    width: 100%;
    height: 82vh;
    .left-layout {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 100%;
      overflow-y: auto;
    }
    .right-layout {
      overflow-y: auto;
      width: 100%;
      height: 100%;
      background-color: rgb(247, 247, 247);
    }
  }
  .bottom-layout{
    margin-top: 10px;
    display: flex;
    justify-content: center;
  }
}
</style>